// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"

package com.pos.modules;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import com.pos.R;
import com.pos.toolbox.file.FilesManager;
import com.pos.widgets.ActionBarManager;
import com.pos.widgets.cropper.CropImage;
import com.pos.widgets.cropper.CropImageOptions;
import com.pos.widgets.cropper.CropImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Built-in activity for image cropping.<br>
 * Use {@link CropImage#activity(Uri)} to create a builder to start this
 * activity.
 */
public class CropImageActivity extends Activity
		implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnCropImageCompleteListener {
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

	/**
	 * The crop image view library widget used in the activity
	 */
	private CropImageView mCropImageView;

	/**
	 * the options that were set for the crop image
	 */
	private CropImageOptions mOptions;
	private Context mContext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.crop_image_activity);
		mContext = this;
		mCropImageView = (CropImageView) findViewById(R.id.cropImageView);

		Intent intent = getIntent();
		Uri source = intent.getParcelableExtra(CropImage.CROP_IMAGE_EXTRA_SOURCE);
		mOptions = intent.getParcelableExtra(CropImage.CROP_IMAGE_EXTRA_OPTIONS);
		mOptions.cropShape = mCropImageView.getCropShape();
		mOptions.guidelines = mCropImageView.getGuidelines();
		mOptions.aspectRatioX = 5;
		mOptions.aspectRatioY = 5;
		if (savedInstanceState == null) {
			mCropImageView.setImageUriAsync(source);
		}
		ActionBarManager.init(this, "裁剪图片", true, "完成", new OnClickListener() {

			@Override
			public void onClick(View v) {
				cropImage();

			}
		});
	}

	@Override
	protected void onStart() {
		super.onStart();
		mCropImageView.setOnSetImageUriCompleteListener(this);
		mCropImageView.setOnCropImageCompleteListener(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		mCropImageView.setOnSetImageUriCompleteListener(null);
		mCropImageView.setOnCropImageCompleteListener(null);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		setResultCancel();
	}

	@Override
	public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
		if (error == null) {
			if (mOptions.initialCropWindowRectangle != null) {
				mCropImageView.setCropRect(mOptions.initialCropWindowRectangle);
			}
			if (mOptions.initialRotation > -1) {
				mCropImageView.setRotatedDegrees(mOptions.initialRotation);
			}
		} else {
			setResult(null, error, 1);
		}
	}

	@Override
	public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) {
//		CropImage.toOvalBitmap(result.getBitmap());
		setResult(result.getUri(), result.getError(), result.getSampleSize());
	}

	// region: Private methods

	/**
	 * Execute crop image and save the result tou output uri.
	 */
	protected void cropImage() {
		if (mOptions.noOutputImage) {
			setResult(null, null, 1);
		} else {
			Uri outputUri = getOutputUri();

			mCropImageView.saveCroppedImageAsync(outputUri, mOptions.outputCompressFormat,
					mOptions.outputCompressQuality, mOptions.outputRequestWidth, mOptions.outputRequestHeight,
					mOptions.outputRequestSizeOptions);
		}
	}

	/**
	 * Rotate the image in the crop image view.
	 */
	protected void rotateImage(int degrees) {
		mCropImageView.rotateImage(degrees);
	}

	/**
	 * Get Android uri to save the cropped image into.<br>
	 * Use the given in options or create a temp file.
	 */
	protected Uri getOutputUri() {
		Uri outputUri = mOptions.outputUri;
		if (outputUri.equals(Uri.EMPTY)) {
			String ext = mOptions.outputCompressFormat == Bitmap.CompressFormat.JPEG ? ".jpg"
					: mOptions.outputCompressFormat == Bitmap.CompressFormat.PNG ? ".png" : ".webp";
			// outputUri = Uri.fromFile(File.createTempFile("cropped", ext,
			// getCacheDir()));
			outputUri = Uri
					.fromFile(new File(FilesManager.getImageFilePath(mContext, format.format(new Date()) + ".png")));
		}
		return outputUri;
	}

	/**
	 * Result with cropped image data or error if failed.
	 */
	protected void setResult(Uri uri, Exception error, int sampleSize) {
		int resultCode = error == null ? RESULT_OK : CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE;
		setResult(resultCode, getResultIntent(uri, error, sampleSize));
		finish();
	}

	/**
	 * Cancel of cropping activity.
	 */
	protected void setResultCancel() {
		setResult(RESULT_CANCELED);
		finish();
	}

	/**
	 * Get intent instance to be used for the result of this activity.
	 */
	protected Intent getResultIntent(Uri uri, Exception error, int sampleSize) {
		CropImage.ActivityResult result = new CropImage.ActivityResult(null, uri, error, mCropImageView.getCropPoints(),
				mCropImageView.getCropRect(), mCropImageView.getRotatedDegrees(), sampleSize);
		Intent intent = new Intent();
		intent.putExtra(CropImage.CROP_IMAGE_EXTRA_RESULT, result);
		return intent;
	}

}
